package zhang.lao.console.controller.common;

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import zhang.lao.build.kit.LogKit;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import zhang.lao.pojo.console.ConsoleContext;
import zhang.lao.pojo.console.resp.HttpResultEnum;
import zhang.lao.pojo.console.resp.HttpResultUtil;
import zhang.lao.pojo.console.select.SelectReq;

import zhang.lao.pojo.console.resp.HttpResult;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/7.
 */
@Controller
public class SelectCommontController {
    private static final List<String> tables = Lists.newArrayList("wn_farm","wn_app_user","sys_dictionary");
    @Resource
    private JdbcTemplate jdbcTemplate;
    @RequestMapping("/console/select/json")
    public @ResponseBody
    HttpResult json(SelectReq selectReq, ConsoleContext consoleContext){
            String where = selectReq.getWhere();
            where=where==null?"":where;
        String tableName = selectReq.getTable().trim().toLowerCase();
        if(tables.contains(tableName)){

        }else{
            return HttpResultUtil.buildError(HttpResultEnum.ROLENOPERMISSION);
        }
            if(tableName.equals("wn_farm")){
            if(StringUtils.isNotBlank(consoleContext.getFarmsInSql())) {
                where = " where id " + consoleContext.getFarmsInSql();
            }else{
                return HttpResultUtil.buildSuccess();
            }
            }
            String sql = "select "+selectReq.getShowValueField()+" as s,"+selectReq.getValueField()+" as v from  "+tableName+" "+where;
            if(tableName.equals("wn_app_user")){
                sql = "select CONCAT("+selectReq.getShowValueField()+", '(',phone_number,')') as s,"+selectReq.getValueField()+" as v from  "+tableName+" "+where;
            }
            return HttpResultUtil.buildSuccess(jdbcTemplate.queryForList(sql));
    }
}
